/**
 * @Author: easten
 * @Created: 2024-04-16 00:32:54
 * @Description: 用户管理
 *
 */
import classnames from "classnames";
import React, { useState, useEffect } from "react";
import { RefreshIcon, SearchIcon } from "tdesign-icons-react";
import {
  Button,
  Input,
  Popconfirm,
  Space,
  Switch,
  Table,
  message,
} from "tdesign-react";
import UserDrawer from "./UserDrawer";
import { ModuleCommonProps, PageParams } from "_common/DataType";
import { SysUser } from "_common/entity";
import { ApiUser } from "_common/api/sys/ApiUser";
import { TableTitle } from "components";
const SysUserComp: React.FC<ModuleCommonProps> = (props: ModuleCommonProps) => {
  const { axios, className } = props;

  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([
    1, 2,
  ]);
  const [loading] = useState<boolean>(false);
  const [userList, setUserList] = useState<SysUser[]>([]);
  const [selectedRow, setSelectedRow] = useState<SysUser>();
  const [userName, setUserName] = useState<string>();
  const [pageState, setPageState] = useState<PageParams>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });

  const [visible, setVisible] = useState(false);
  const [edit, setEdit] = useState(false);
  const apiUser = new ApiUser(axios!);
  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  useEffect(() => {
    getUserList();
  }, [userName]);

  const getUserList = async () => {
    const response = await apiUser.getPageList({
      ...pageState,
      userName,
    });
    if (response && response.code == 200 && response.data) {
      setUserList(response.data.list);
      setPageState({
        ...pageState,
        total: response.data.total,
        list: response.data.list,
      });
    }
  };

  // 删除用户
  const deleteUser = async (id: number) => {
    const response = await apiUser.deleteUser(id);
    if (response && response.code == 200 && response.data) {
      message.success("删除成功");
      getUserList();
    }
  };

  // 修改用户状态
  const updateUserStatus = async (id: number, status: boolean) => {
    const response = await apiUser.changeStatus({ id, status });
    if (response && response.code == 200 && response.data) {
      message.success(`用户状态${status ? "启用" : "禁用"}成功`);
      getUserList();
    }
  };

  return (
    <div className={classnames(className)}>
      <div className="flex flex-row justify-between mb-4">
        <TableTitle text="用户列表" />
        <Space size={5}>
          <Input
            suffixIcon={<SearchIcon />}
            placeholder="请输入要搜索的用户名称"
            onChange={(v) => {
              setUserName(v);
            }}
          />
          <Button
            onClick={() => {
              setVisible(true);
              setEdit(false);
            }}
          >
            添加用户
          </Button>
          <Button
            icon={<RefreshIcon />}
            variant="outline"
            onClick={() => {
              getUserList();
            }}
          ></Button>
        </Space>
      </div>
      <Table<SysUser>
        bordered
        columns={[
          {
            align: "left",
            width: 80,
            ellipsis: true,
            colKey: "index",
            title: "序号",
            cell: ({ rowIndex }) => {
              let _index =
                (pageState.pageNum - 1) * pageState.pageSize + rowIndex + 1;
              return <span>{_index}</span>;
            },
          },
          {
            align: "left",
            ellipsis: true,
            colKey: "account",
            title: "账号",
          },
          {
            align: "left",
            ellipsis: true,
            colKey: "name",
            title: "用户名称",
          },

          {
            align: "left",
            ellipsis: true,
            colKey: "email",
            title: "邮箱",
          },
          {
            align: "center",
            width: 120,
            ellipsis: true,
            colKey: "gender",
            title: "性别",
            cell: ({ row }) => {
              return <span>{row.gender == "1" ? "男" : "女"}</span>;
            },
          },
          {
            align: "center",
            width: 120,
            ellipsis: true,
            colKey: "status",
            title: "状态",
            cell: ({ row }) => {
              return (
                <Switch
                  value={row.status}
                  onChange={(e) => {
                    updateUserStatus(row.id, e);
                  }}
                  size="small"
                />
              );
            },
          },
          {
            align: "left",
            ellipsis: true,
            colKey: "createTime",
            title: "创建时间",
            cell({ row }) {
              return <span>{row.createTime ?? "-"}</span>;
            },
          },
          {
            align: "center",
            fixed: "right",
            width: 220,
            colKey: "op",
            title: "操作",
            cell({ row }) {
              return (
                <>
                  <Button
                    theme="success"
                    variant="text"
                    onClick={() => {
                      setVisible(true);
                      setEdit(true);
                      setSelectedRow(row);
                    }}
                  >
                    编辑
                  </Button>
                  <Popconfirm
                    content="确认删除吗"
                    destroyOnClose
                    placement="top"
                    showArrow
                    theme="default"
                    onConfirm={() => deleteUser(row.id)}
                  >
                    <Button theme="primary" variant="text">
                      删除
                    </Button>
                  </Popconfirm>
                </>
              );
            },
          },
        ]}
        loading={loading}
        data={userList}
        rowKey="index"
        selectedRowKeys={selectedRowKeys}
        verticalAlign="middle"
        hover
        onSelectChange={onSelectChange}
        pagination={{
          pageSize: pageState.pageSize,
          total: pageState.total,
          current: pageState.pageNum,
          showJumper: true,
          onCurrentChange(current) {
            setPageState({
              ...pageState,
              pageNum: current,
            });
          },
          onPageSizeChange(size) {
            setPageState({
              ...pageState,
              pageSize: size,
            });
          },
        }}
      />
      <UserDrawer
        axios={axios}
        open={visible}
        edit={edit}
        value={selectedRow}
        onSuccess={() => {
          setVisible(false);
          getUserList();
        }}
      />
    </div>
  );
};
export default SysUserComp;
